#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/10/26
# @Author  : 邓大大
# @Desc    : ccxt 三角套利策略

# 策略: 选择两个计价币，一个套利币
# 公式: 计价币A 买计价币B 再通过计价币B买套利币C 最后 卖出套利币C兑换称计价币A
#      A 、     A/Pb、         (A/Pb)/Pcb             (A/Pb)/Pc * pca
# 获利公式： P3/(P1*P2) - 1
import ccxt
import pandas as pd


def main():
    """主函数"""
    # 初始化交易所
    binance_exchange = ccxt.binance({
        'timeout': 15000,
        'enableRateLimit': True,
        'proxies': {
            'http': 'http://127.0.0.1:58591',
            'https': 'https://127.0.0.1:58591'}
    })

    # 加载行情
    markets = binance_exchange.load_markets()

    # 步骤一、选择两个交易市场
    market_a = 'BTC'
    market_b = 'ETH'
    # 步骤二、找到所有A、B同时可以作为计价的货币
    symbols = list(markets.keys())
    # 存放到DataFrame中
    symbols_df = pd.DataFrame(data=symbols, columns=['symbol'])
    # 分割字符串得到 基础货币/计价货币
    base_quote_df = symbols_df['symbol'].str.split('/', expand=True)
    base_quote_df.columns = ['base', 'quote']
    base_a_list = base_quote_df[base_quote_df['quote'] == market_a]['base'].values.tolist()  # 以计价币A计价的货币列表
    base_b_list = base_quote_df[base_quote_df['quote'] == market_b]['base'].values.tolist()  # 以计价币B计价的货币列表
    common_base_list = list(set(base_a_list).intersection(set(base_b_list)))
    print('{}和{}共有{}个相同的计价货币{}:'.format(market_a, market_b, len(common_base_list), common_base_list))
    # 步骤三： 执行套利步骤
    colums = [
        'Market_A',
        'Market_B',
        'Market_C',
        'P1',
        'P2',
        'P3',
        'Profit(%o)'
    ]
    results_df = pd.DataFrame(columns=colums)

    last_min = binance_exchange.milliseconds() - 180 * 1000
    for base_coin in common_base_list:
        market_c = base_coin
        market_a2b_symbol = '{}/{}'.format(market_b, market_a)
        market_b2c_symbol = '{}/{}'.format(market_c, market_b)
        market_a2c_symbol = '{}/{}'.format(market_c, market_a)

        # 获取行情前一分钟的K线数据
        market_a2b_kline = binance_exchange.fetch_ohlcv(market_a2b_symbol, since=last_min, timeframe='1m')
        market_b2c_kline = binance_exchange.fetch_ohlcv(market_b2c_symbol, since=last_min, timeframe='1m')
        market_a2c_kline = binance_exchange.fetch_ohlcv(market_a2c_symbol, since=last_min, timeframe='1m')
        print(market_a2c_kline)
        # if len(market_a2c_kline) == 0 or len(market_b2c_kline) == 0 or len(market_a2b_kline) == 0:
        #     continue
        # # 同一时刻三个价格
        # p1 = market_a2b_kline[0][4]
        # p2 = market_b2c_kline[0][4]
        # p3 = market_a2c_kline[0][4]
        #
        # # 差价
        # profit = (p3 / (p1 * p2) - 1) * 1000
        #
        # results_df = results_df.append({
        #     'Market_A': market_a,
        #     'Market_B': market_b,
        #     'Market_C': market_c,
        #     'P1': p1,
        #     'P2': p2,
        #     'P3': p3,
        #     'Profit(%o)': profit
        # }, ignore_index=True)
        # print(results_df.tail(1))

    # results_df.to_csv('tri_arbitrage_results.csv', index=None)


if __name__ == '__main__':
    main()
